# -*- coding: utf-8 -*-

"""
# @Time    : 2021/7/6 19:41
# @User  : Mabin
# @Descriotion  :身份令牌相关的生成和校验
"""
import base64
import hashlib
import hmac
import json
import time
from application.constant import MEDPEER_PUBLIC_KEY


class Token:
    # 身份令牌过期时间（秒）
    _expire_time = 10

    @classmethod
    def gen_token_info(cls, secret=''):
        """
        生成身份令牌
        :author Mabin
        :param str secret:密钥
        """
        if not secret:
            secret = MEDPEER_PUBLIC_KEY

        header = base64.b64encode(json.dumps({"typ": "JWT", "alg": "HS256"}).encode('utf-8'))
        payload = base64.b64encode(json.dumps({
            "iat": int(time.time()),
            "exp": int(time.time()) + cls._expire_time
        }).encode('utf-8'))
        signature = base64.b64encode(
            hmac.new(secret.encode('utf-8'), header + payload, hashlib.sha256).hexdigest().encode('utf-8')
        )

        return header.decode(encoding='utf-8') + "." + payload.decode(encoding='utf-8') + "." + signature. \
            decode(encoding='utf-8')

    @staticmethod
    def validate_token_info(str_token, secret=''):
        """
        验证身份令牌
        :author Mabin
        :param str str_token:待验证的身份令牌
        :param str secret:密钥
        """
        if not str_token:
            return False

        str_token = str(str_token).split(".")
        if len(str_token) != 3:
            return False

        # 获取载荷数组
        payload = json.loads(base64.b64decode(str_token[1]))
        if "exp" not in payload:
            return False
        if payload["exp"] < int(time.time()):
            return False

        # 校验身份令牌的合法性
        if not secret:
            secret = MEDPEER_PUBLIC_KEY
        signature = base64.b64encode(
            hmac.new(secret.encode('utf-8'), str_token[0].encode('utf-8') + str_token[1].encode('utf-8'),
                     hashlib.sha256).hexdigest().encode('utf-8')
        ).decode()
        if str_token[2] != signature:
            return False

        return True
